package com.mtao.impl;

import com.mtao.LoginService;
import com.mtao.SysRoleUserService;
import com.mtao.dto.UserDto;
import com.mtao.utils.JwtUtils;
import com.mtao.entity.SysUser;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private SysRoleUserService sysRoleUserService;

    @Resource
    private JwtUtils jwtUtils;


    @Override
    public HashMap login(UserDto userDto, SysUser user){
        //  获取当前用户角色
        HashMap rolesMap = sysRoleUserService.getRolesByUserId(user.getId());
        List<String> roles = (List<String>) rolesMap.get("roles");
        List<Integer> rolesIds = (List<Integer>) rolesMap.get("rolesIds");
        //  生成token
        String token = jwtUtils.createJwt(user, roles, false);

        //  生成refresh_token
        String refreshToken = jwtUtils.getRefreshToken(user.getUsername());
        //  用户信息
        userDto.setId(user.getId());
        userDto.setEmail(user.getEmail());
        userDto.setEnabled(user.getEnabled());
        userDto.setCreateTime(user.getCreateTime());
        userDto.setUpdateTime(user.getUpdateTime());
        userDto.setImg(user.getImg());
        userDto.setRoleIds(rolesIds);
        userDto.setNickName(user.getNickName());
        userDto.setRoles(roles);
        //  隐藏密码
        userDto.setPassword("******");
        HashMap loginObj = new HashMap();
        loginObj.put("token",token);
        loginObj.put("refreshToken",refreshToken);
        loginObj.put("userInfo",userDto);
        return loginObj;
    }
}
